/*
 * Copyright 2002-2018 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.beans.factory.xml;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.LinkedHashSet;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.parsing.BeanComponentDefinition;
import org.springframework.beans.factory.support.BeanDefinitionReaderUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.ResourcePatternUtils;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;

/**
 * Default implementation of the {@link BeanDefinitionDocumentReader} interface that
 * reads bean definitions according to the "spring-beans" DTD and XSD format
 * (Spring's default XML bean definition format).
 *
 * <p>The structure, elements, and attribute names of the required XML document
 * are hard-coded in this class. (Of course a transform could be run if necessary
 * to produce this format). {@code <beans>} does not need to be the root
 * element of the XML document: this class will parse all bean definition elements
 * in the XML file, regardless of the actual root element.
 *
 * @author Rod Johnson
 * @author Juergen Hoeller
 * @author Rob Harrop
 * @author Erik Wiersma
 * @since 18.12.2003
 */

/**
 * BeanDefinitionDocumentReader接口的默认实现类，
 * 用于读取Spring默认的XML bean定义格式（"spring-beans" DTD/XSD）。
 * 此类硬编码了所需XML文档的结构、元素和属性名称。
 * <beans>不需要是XML文档的根元素：此类将解析XML文件中的所有bean定义元素。
 */
public class DefaultBeanDefinitionDocumentReader implements BeanDefinitionDocumentReader {

	// XML元素和属性常量
	public static final String BEAN_ELEMENT = BeanDefinitionParserDelegate.BEAN_ELEMENT;  // "bean"元素
	public static final String NESTED_BEANS_ELEMENT = "beans";  // 嵌套的beans元素
	public static final String ALIAS_ELEMENT = "alias";  // 别名元素
	public static final String NAME_ATTRIBUTE = "name";  // name属性
	public static final String ALIAS_ATTRIBUTE = "alias";  // alias属性
	public static final String IMPORT_ELEMENT = "import";  // import元素
	public static final String RESOURCE_ATTRIBUTE = "resource";  // resource属性
	public static final String PROFILE_ATTRIBUTE = "profile";  // profile属性

	protected final Log logger = LogFactory.getLog(getClass());  // 日志记录器

	@Nullable
	private XmlReaderContext readerContext;  // XML读取上下文

	@Nullable
	private BeanDefinitionParserDelegate delegate;  // bean定义解析委托类


	/**
	 * This implementation parses bean definitions according to the "spring-beans" XSD
	 * (or DTD, historically).
	 * <p>Opens a DOM Document; then initializes the default settings
	 * specified at the {@code <beans/>} level; then parses the contained bean definitions.
	 */
	/**
	 * 根据"spring-beans" XSD（或DTD）解析bean定义。
	 * 打开DOM文档，初始化<beans>级别指定的默认设置，然后解析包含的bean定义。
	 */
	@Override
	public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
		this.readerContext = readerContext;
		doRegisterBeanDefinitions(doc.getDocumentElement());  // 从文档根元素开始注册bean定义
	}

	/**
	 * Return the descriptor for the XML resource that this parser works on.
	 */
	/**
	 * 获取此解析器正在处理的XML资源的描述符
	 */
	protected final XmlReaderContext getReaderContext() {
		Assert.state(this.readerContext != null, "No XmlReaderContext available");
		return this.readerContext;
	}

	/**
	 * Invoke the {@link org.springframework.beans.factory.parsing.SourceExtractor}
	 * to pull the source metadata from the supplied {@link Element}.
	 */
	/**
	 * 从给定元素提取源元数据
	 */
	@Nullable
	protected Object extractSource(Element ele) {
		return getReaderContext().extractSource(ele);
	}


	/**
	 * Register each bean definition within the given root {@code <beans/>} element.
	 */
	/**
	 * 注册给定根<beans>元素中的每个bean定义
	 */
	@SuppressWarnings("deprecation")  // for Environment.acceptsProfiles(String...)
	protected void doRegisterBeanDefinitions(Element root) {
		// 处理嵌套的<beans>元素会导致递归调用此方法。
		// 为了正确传播和保留<beans>的default-*属性，
		// 需要跟踪当前(父)委托，可能为null。
		BeanDefinitionParserDelegate parent = this.delegate;
		this.delegate = createDelegate(getReaderContext(), root, parent);

		// 检查profile属性，决定是否应该处理这个配置文件
		if (this.delegate.isDefaultNamespace(root)) {
			String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE);
			if (StringUtils.hasText(profileSpec)) {
				String[] specifiedProfiles = StringUtils.tokenizeToStringArray(
						profileSpec, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS);
				// 不能使用Profiles.of(...)，因为XML配置不支持profile表达式
				if (!getReaderContext().getEnvironment().acceptsProfiles(specifiedProfiles)) {
					if (logger.isDebugEnabled()) {
						logger.debug("Skipped XML bean definition file due to specified profiles [" + profileSpec +
								"] not matching: " + getReaderContext().getResource());
					}
					return;
				}
			}
		}

		// 预处理XML（模板方法，默认空实现）
		preProcessXml(root);
		// 实际解析bean定义
		parseBeanDefinitions(root, this.delegate);
		// 后处理XML（模板方法，默认空实现）
		postProcessXml(root);

		// 恢复父委托
		this.delegate = parent;
	}

	/**
	 * 创建BeanDefinitionParserDelegate实例
	 */
	protected BeanDefinitionParserDelegate createDelegate(
			XmlReaderContext readerContext, Element root, @Nullable BeanDefinitionParserDelegate parentDelegate) {

		BeanDefinitionParserDelegate delegate = new BeanDefinitionParserDelegate(readerContext);
		delegate.initDefaults(root, parentDelegate);  // 初始化默认设置
		return delegate;
	}

	/**
	 * Parse the elements at the root level in the document:
	 * "import", "alias", "bean".
	 * @param root the DOM root element of the document
	 */
	/**
	 * 解析文档根级别的元素：import、alias、bean
	 */
	protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
		if (delegate.isDefaultNamespace(root)) {
			// 在默认命名空间下处理子元素
			NodeList nl = root.getChildNodes();
			for (int i = 0; i < nl.getLength(); i++) {
				Node node = nl.item(i);
				if (node instanceof Element) {
					Element ele = (Element) node;
					if (delegate.isDefaultNamespace(ele)) {
						/**
						 * 解析默认的命名空间的流程是
						 * 1.在processBeanDefinition(ele, delegate);处理BeanDefinition的入口
						 * 2.parseBeanDefinitionElement(ele) 方法里面解析XMl内容，并且处理Bean标签，
						 *   且会生成一个对象BeanDefinitionHolder(这个专门用来存BeanDefinition的定义信息，自定义命名空间也是用这个类接收)
						 * 3.registerBeanDefinition(bdHolder, getReaderContext().getRegistry())；在这里按完成
						 * BeanDefinition放入到容器中(BeanDefinition)
						 *
						 */
						parseDefaultElement(ele, delegate);  // 解析默认命名空间元素
					} else {
						/**
						 * 解析自定义的命名空间的流程是
						 * 1.在parseCustomElement()中调用handler.parse(ele, new ParserContext(this.readerContext, this, containingBd));进行解析
						 * 2.在上面方法中调用重载parse(Element element, ParserContext parserContext)
						 * 3.会在上面的方法里面进行XMl的解析，并且把解析出来的内容放入BeanDefinition中，
						 *   然后还会把BeanDefinition信息，直接放入到BeanFactory中
						 *
						 */
						delegate.parseCustomElement(ele);  // 解析自定义命名空间元素
					}
				}
			}
		} else {
			// 在自定义命名空间下处理根元素
			delegate.parseCustomElement(root);
		}
	}

	/**
	 * 解析默认命名空间下的元素
	 */
	private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {
		if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) {
			importBeanDefinitionResource(ele);  // 处理import元素
		} else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) {
			processAliasRegistration(ele);  // 处理alias元素
		} else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) {
			processBeanDefinition(ele, delegate);  // 处理bean元素
		} else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {
			// 递归处理嵌套的beans元素
			doRegisterBeanDefinitions(ele);
		}
	}

	/**
	 * Parse an "import" element and load the bean definitions
	 * from the given resource into the bean factory.
	 */
	/**
	 * 解析import元素并从给定资源加载bean定义到bean工厂
	 */
	protected void importBeanDefinitionResource(Element ele) {
		String location = ele.getAttribute(RESOURCE_ATTRIBUTE);
		if (!StringUtils.hasText(location)) {
			getReaderContext().error("Resource location must not be empty", ele);
			return;
		}

		// 解析系统属性：例如"${user.dir}"
		location = getReaderContext().getEnvironment().resolveRequiredPlaceholders(location);

		Set<Resource> actualResources = new LinkedHashSet<>(4);

		// 判断location是绝对URI还是相对URI
		boolean absoluteLocation = false;
		try {
			absoluteLocation = ResourcePatternUtils.isUrl(location) || ResourceUtils.toURI(location).isAbsolute();
		} catch (URISyntaxException ex) {
			// 无法转换为URI，视为相对路径（除非是已知的Spring前缀"classpath*:"）
		}

		// 处理绝对或相对路径
		if (absoluteLocation) {
			try {
				// 加载绝对路径资源
				int importCount = getReaderContext().getReader().loadBeanDefinitions(location, actualResources);
				if (logger.isTraceEnabled()) {
					logger.trace("Imported " + importCount + " bean definitions from URL location [" + location + "]");
				}
			} catch (BeanDefinitionStoreException ex) {
				getReaderContext().error(
						"Failed to import bean definitions from URL location [" + location + "]", ele, ex);
			}
		} else {
			// 处理相对路径资源
			try {
				int importCount;
				Resource relativeResource = getReaderContext().getResource().createRelative(location);
				if (relativeResource.exists()) {
					importCount = getReaderContext().getReader().loadBeanDefinitions(relativeResource);
					actualResources.add(relativeResource);
				} else {
					String baseLocation = getReaderContext().getResource().getURL().toString();
					importCount = getReaderContext().getReader().loadBeanDefinitions(
							StringUtils.applyRelativePath(baseLocation, location), actualResources);
				}
				if (logger.isTraceEnabled()) {
					logger.trace("Imported " + importCount + " bean definitions from relative location [" + location + "]");
				}
			} catch (IOException ex) {
				getReaderContext().error("Failed to resolve current resource location", ele, ex);
			} catch (BeanDefinitionStoreException ex) {
				getReaderContext().error(
						"Failed to import bean definitions from relative location [" + location + "]", ele, ex);
			}
		}
		Resource[] actResArray = actualResources.toArray(new Resource[0]);
		getReaderContext().fireImportProcessed(location, actResArray, extractSource(ele));
	}

	/**
	 * Process the given alias element, registering the alias with the registry.
	 */
	/**
	 * 处理给定的alias元素，向注册表注册别名
	 */
	protected void processAliasRegistration(Element ele) {
		String name = ele.getAttribute(NAME_ATTRIBUTE);
		String alias = ele.getAttribute(ALIAS_ATTRIBUTE);
		boolean valid = true;
		if (!StringUtils.hasText(name)) {
			getReaderContext().error("Name must not be empty", ele);
			valid = false;
		}
		if (!StringUtils.hasText(alias)) {
			getReaderContext().error("Alias must not be empty", ele);
			valid = false;
		}
		if (valid) {
			try {
				// 向注册表注册别名
				getReaderContext().getRegistry().registerAlias(name, alias);
			} catch (Exception ex) {
				getReaderContext().error("Failed to register alias '" + alias +
						"' for bean with name '" + name + "'", ele, ex);
			}
			getReaderContext().fireAliasRegistered(name, alias, extractSource(ele));
		}
	}

	/**
	 * Process the given bean element, parsing the bean definition
	 * and registering it with the registry.
	 */
	/**
	 * 处理给定的bean元素，解析bean定义并注册到注册表
	 */
	protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
		// 解析bean元素,且吧bean的信息放入了BeanDefinition中   BeanDefinitionHolder(这个是我们BeanDefinition的具体实现)
		//在这里开始，xml文件已经被解析成Element对象，从这里面拿数据解析到BeanDefinition中
		BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
		if (bdHolder != null) {
			// 装饰bean定义（如果需要）
			bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
			try {
				// 注册最终装饰后的实例,也是在这吧BeanDefinition信息放入到IOC(beanFactory中)
				BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
			} catch (BeanDefinitionStoreException ex) {
				getReaderContext().error("Failed to register bean definition with name '" +
						bdHolder.getBeanName() + "'", ele, ex);
			}
			// 发送注册事件
			getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
		}
	}


	/**
	 * Allow the XML to be extensible by processing any custom element types first,
	 * before we start to process the bean definitions. This method is a natural
	 * extension point for any other custom pre-processing of the XML.
	 * <p>The default implementation is empty. Subclasses can override this method to
	 * convert custom elements into standard Spring bean definitions, for example.
	 * Implementors have access to the parser's bean definition reader and the
	 * underlying XML resource, through the corresponding accessors.
	 * @see #getReaderContext()
	 */
	/**
	 * 预处理XML的模板方法（默认空实现）。
	 * 允许在开始处理bean定义之前先处理任何自定义元素类型。
	 * 子类可以覆盖此方法将自定义元素转换为标准Spring bean定义。
	 */
	protected void preProcessXml(Element root) {
	}

	/**
	 * Allow the XML to be extensible by processing any custom element types last,
	 * after we finished processing the bean definitions. This method is a natural
	 * extension point for any other custom post-processing of the XML.
	 * <p>The default implementation is empty. Subclasses can override this method to
	 * convert custom elements into standard Spring bean definitions, for example.
	 * Implementors have access to the parser's bean definition reader and the
	 * underlying XML resource, through the corresponding accessors.
	 * @see #getReaderContext()
	 */
	/**
	 * 后处理XML的模板方法（默认空实现）。
	 * 允许在完成bean定义处理后最后处理任何自定义元素类型。
	 * 子类可以覆盖此方法将自定义元素转换为标准Spring bean定义。
	 */
	protected void postProcessXml(Element root) {
	}
}